﻿using System;
using Basmus.ReadWrite;

namespace Basmus.Values.Attributive.ReadWrite
{
    public class EnumObjectElementsReaderWriterBuilder : IObjectElementsReaderWriterBuilder
    {
        private readonly IBindingBuilder _bindingBuilder;

        public EnumObjectElementsReaderWriterBuilder(IBindingBuilder bindingBuilder)
        {
            _bindingBuilder = bindingBuilder;
        }

        public IElementsReaderWriter<object> Build(ValuesContext valuesContext)
        {
            var elementType = _bindingBuilder.Build(valuesContext).ElementType;
            if (elementType.IsEnum)
            {
                var enumReaderWriter = typeof (EnumReaderWriter<>)
                    .MakeGenericType(elementType)
                    .GetConstructor(new Type[0])
                    .Invoke(null);
                object objectElementsReaderWriter = ReflectionHelper.GetObjectElementsReaderWriter(elementType, enumReaderWriter);
                return (IElementsReaderWriter<object>)objectElementsReaderWriter;
            }
            return null;
        }
    }
}